package com.imooc.api.support;

import com.imooc.bilibili.domain.exception.ConditionException;
import com.imooc.bilibili.util.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * ProjectName imooc-bilibili
 *
 * @author xieyucan
 * <br>CreateDate 2022/10/22 14:43
 */
@Component
public class UserSupport {

    //获取当前用户id
    public Long getCurrentUserId()
    {
        //获取请求相关上下文信息
        //通过ServletRequestAttributes获取到请求相关信息
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        //在请求中获取到请求头，token
        String token = requestAttributes.getRequest().getHeader("token");
        //通过token解析获取用户id
        Long userId = TokenUtil.verifyToken(token);
        if(userId<0){
            throw new ConditionException("非法用户!");
        }
        //返回用户id
        return userId;
    }
}
